package com.gusti.admincasa.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gusti.admincasa.dao.IPortDao;
import com.gusti.admincasa.model.Port;
import com.gusti.admincasa.util.Debug;

/**
 * 
 * @author gusti
 *
 */
@Repository
public class PortDao extends ProjectDao<Port> implements IPortDao  {

	public Port findPort( long id ) {
		Port port = new Port();

		Query query = null;
		try {
			query = em.createQuery( "FROM Port as p WHERE p.id = :portId" );
			query.setParameter( "portId", id );
			port = (Port)query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
		}

		return port;
	}

	@SuppressWarnings("unchecked")
	public List<Port> listPorts() {
		List<Port> ports = new ArrayList<Port>();

		Query query = null;
		try {
			query = em.createQuery( "FROM Port" );
			ports = (List<Port>)query.getResultList();
		} catch ( Exception e ) {
			Debug.error( e );
		}

		return ports;
	}

	public int getPortStatus() {
		Long number = new Long(0);

		Query query = null;
		try {
			query = em.createQuery( "SELECT SUM(p.value) FROM Port p WHERE p.activated = true" );
			number = (Long)query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
		}

		if( number == null ) {
			number = new Long(0);
		}

		return number.intValue();
	}

	public void resetPortStatus() {
		Query query = null;
		try {
			query = em.createQuery( "UPDATE Port p set p.activated = false" );
			int result = (int)query.executeUpdate();
			Debug.log( result + "" );
		} catch ( Exception e ) {
			Debug.error( e );
		}
	}
}
